document.addEventListener('DOMContentLoaded', function() {
    const messageDiv = document.getElementById('message');
    const regionsTableBody = document.getElementById('regionsTable').getElementsByTagName('tbody')[0];
    const current_id = getCookie("id");

    async function fetchRegions() {
        const response = await fetch('/region/array');
        if (response.ok) {
            return await response.json();
        } else {
            throw new Error('Не удалось загрузить список регионов.');
        }
    }

    function getCookie(name) {
        const value = `; ${document.cookie}`;
        const parts = value.split(`; ${name}=`);
        if (parts.length === 2) return parts.pop().split(';').shift();
    }

    function renderRegions(regions) {
        regionsTableBody.innerHTML = '';
        regions.forEach(region => {
            const row = regionsTableBody.insertRow();
            ['id', 'name', 'parentRegion', 'regionType', 'latitude', 'longitude', 'accountId'].forEach(field => {
                const cell = row.insertCell();
                const input = document.createElement('input');
                input.type  = 'text';

                if (field === "regionType") {
                    const a = document.createElement('a');
                    a.href = `/regions/types?id=${region[field]}`
                    a.text = region[field];

                    input.appendChild(a);
                }

                input.value = region[field];
                input.disabled = false;

                input.id   = field;
                input.name = field;

                cell.appendChild(input);
            });

            const actionsCell = row.insertCell();
            const viewBtn = document.createElement('button');
            viewBtn.textContent = '🔍';
            viewBtn.title = 'Просмотр региона';
            viewBtn.onclick = () => viewRegion(region.id);
            actionsCell.appendChild(viewBtn);

            const deleteBtn = document.createElement('button');
            deleteBtn.textContent = '❌';
            deleteBtn.title = 'Удалить регион';
            deleteBtn.onclick = () => deleteRegion(region.id);
            actionsCell.appendChild(deleteBtn);
        });
    }

    async function deleteRegion(id) {
        try {
            const response = await fetch(`/regions/${id}`, {
                method: 'DELETE'
            });
            if (response.ok) {
                showMessage('Регион удален успешно.', 'success');
                loadRegions();
            } else {
                showMessage('Ошибка удаления региона: ' + (await response.json()).detail, 'error');
            }
        } catch (error) {
            showMessage('Ошибка удаления региона: ' + error.message, 'error');
        }
    }

    window.createRegion = async function() {
        const form = document.getElementById('regionForm');
        const formData = new FormData(form);
        const data = Object.fromEntries(formData.entries());
        data["accountId"] = current_id;

        try {
            const response = await fetch('/region', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(data)
            });
            if (response.ok) {
                showMessage('Регион создан успешно.', 'success');
                loadRegions();
                form.reset();
            } else {
                showMessage('Ошибка создания региона: ' + (await response.json()).detail, 'error');
            }
        } catch (error) {
            showMessage('Ошибка создания региона: ' + error.message, 'error');
        }
    }

    function showMessage(message, type) {
        messageDiv.textContent = message;
        messageDiv.className = `message ${type}`;
        messageDiv.style.display = 'block';
        setTimeout(() => {
            messageDiv.style.display = 'none';
        }, 5000);
    }

    function viewRegion(id) {
        window.location.href = `/region?id=${id}`;
    }

    async function loadRegions() {
        try {
            const regions = await fetchRegions();
            renderRegions(regions);
        } catch (error) {
            showMessage(error.message, 'error');
        }
    }

    loadRegions();
});